<template>
  <a-row :gutter="24" class="search-row">
    <a-col :span="24">
      <x-card>
        <div slot="content" class="table-page-search-wrapper" ref="myElement">
          <a-form layout="inline">
            <a-row :gutter="24">
              <a-col :span="10">
                <a-form-item label="隐患单位" required :labelCol="{ style: 'width:115px' }">
                  <a-cascader
                    ref="orgTree"
                    tree-node-filter-prop="title"
                    :tree-check-strictly="true"
                    :show-search="true"
                    :show-all-levels="false"
                    style="width: 100%"
                    :dropdownStyle="{ maxHeight: 600, overflow: 'auto' }"
                    placeholder="请选择隐患单位"
                    allow-clear
                    :options="unitTree"
                    @change="handleOrganNameClick"
                    treeCheckStrictly
                    :rules="[{ required: true, message: '请选择隐患单位' }]"
                    :title="queryParam.DangerOrganizationName"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="3">
                <a-form-item
                  style="width: 100%"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                >
                  <!-- 上传文档组件 -->
                  <a-upload
                    :beforeUpload="beforeUpload"
                    @change="handleFileChange"
                  >
                    <a-button>
                      <a-icon type="upload" /> 点击上传文档
                    </a-button>
                  </a-upload>
                </a-form-item>
              </a-col>
              <a-col :span="2" class="search-buttons" style="margin-left: -5px;">
                <a-button type="primary" @click="handleDownloadTemplate">
                  <a-icon type="download" />下载模板
                </a-button>
              </a-col>
              <a-col :span="2" style="margin-left: -5px;">
                <a-button
                  type="primary"
                  :loading="loading1"
                  @click="handleclick"
                >
                  {{ loading1 ? '提交中...' : '确认提交Excel' }}
                </a-button>
              </a-col>
            </a-row>
          </a-form>
        </div>
      </x-card>
      <a-card :bordered="false" style="margin-top: -5px;">
        <a-col :span="10">
          <div style="border: 1px solid #ffcccc; background-color: #ffe6e6; padding: 10px;">
            操作流程<br>
            1. 在页面中首先点击下载模板,下载完成后填写数据<br>
            2. 填写完数据后点击上传文件按钮并选择对应的单位<br>
            3. 单击确认提交Ecxel按钮后数据会展示在下方表格中<br>
            4. 进行数据确认以及批量提交操作<br>
            <br>
          </div>
        </a-col>
        <a-col :span="10">
          <div style="border: 1px solid #ffcccc; background-color: #ffe6e6; padding: 10px;">
            注意事项<br>
            1. 请务必确保所有数据的准确性。<br>
            2. 所有的操作请一次性完成,不要中途退出<br>
            3. 不完善的信息提示后会放在表格的最前边的行中<br>
            4. 提交数据最好不要超过30条<br>
            5. 请勿删除模版中的样例数据<br>
          </div>
        </a-col>
        <!-- 添加其他内容或表格 -->
        <a-table
          ref="table"
          :columns="columns"
          :dataSource="loadData"
          :alert="null"
          :pagination="false"
          :rowKey="(record, index) => index"
          :rowSelection="rowSelection"
          :loading="tableLoading"
          filterMultiple
          bordered
          style="margin-top: 20px"
          :key="tableKey"
        >
          <span slot="action" slot-scope="text, record">
            <a-button size="small" style="color: #1d39c4;background-color: #f0f5ff;border-color: #adc6ff; margin-left: 5px;">
              <a @click="$refs.danQRSJ.edit(record)">
                <a-icon type="edit" />
                确认数据</a>
            </a-button>
          </span>
        </a-table>
        <a-button
          type="primary"
          :loading="loading"
          @click="submitSelectedRows"
          style="margin-top: 20px;"
        >
          {{ loading ? '提交中...' : '一键批量提交' }}
        </a-button>
        <danQRSJ ref="danQRSJ" @ok="handleOk" />
      </a-card>
    </a-col>
  </a-row>
</template>

<script>
import { Cascader, Upload, Button } from 'ant-design-vue'
import { STable, XCard, XDown } from '@/components'
import { getUnitTree } from '@/api/modular/system/violationManage'
import { getQHSEDangerSelectUpload, gAddBatchList } from '@/api/modular/system/QHSEHazardQuery'
import danQRSJ from './danQRSJ.vue'
import { mapGetters } from 'vuex'

export default {
  components: {
    XDown,
    XCard,
    STable,
    danQRSJ,
    'a-cascader': Cascader,
    'a-upload': Upload,
    'a-button': Button
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      queryParam: {
        fileName: '',
        file: {
          name: '',
          base64Content: ''
        },
        DangerOrganizationId: '',
        DangerOrganizationName: ''
      },
      tableKey: 0,
      queryParam1: {
        selectedRowKeys: [],
        selectedRows: []
      },
      rowSelection: {
        onChange: (selectedRowKeys, selectedRows) => {
          // 检查 selectedRowKeys 和 selectedRows 是否正确
          // console.log('Selected Row Keys: ', selectedRowKeys)
          // console.log('Selected Rows: ', selectedRows)

          this.queryParam1.selectedRowKeys = selectedRowKeys
          this.queryParam1.selectedRows = selectedRows
        },
        getCheckboxProps: (record) => ({
          // 设置行的checkbox属性
          disabled: record.name // 检查拼写，应该是 disabled
        })
      },
      localPagination: {
        current: 1,
        pageSize: 10,
        total: 0,
        showSizeChanger: true,
        hideOnSinglePage: false
      },
      localLoading: false,
      loading: false,
      loading1: false,
      tableLoading: false,
      localDataSource: [],
      showPagination: true,
      show: false,
      secondOraName: {
        id: ''
      },
      unitTree: [],
      columns: [
        {
          title: '序号',
          customRender: (text, record, index) => `${index + 1}`
        },
        {
          title: '检查时间',
          dataIndex: 'checkDate',
          customRender: (text, record) => {
            if (record.checkDate) {
              const dateParts = record.checkDate.split('T')[0].split('-')
              return `${dateParts[0]}-${dateParts[1]}-${dateParts[2]}`
            }
            return ''
          }
        },
        {
          title: '检查人员',
          dataIndex: 'checkName'
        },
        {
          title: '隐患单位',
          dataIndex: 'organizationName'
        },
        {
          title: '隐患区域',
          dataIndex: 'location'
        },
        {
          title: '隐患性质',
          dataIndex: 'dangerType',
          customRender: function(text) {
            if (text === '重大隐患') {
              return <span style={{ color: 'red' }}>{text}</span>
            } else if (text === '较大隐患') {
              return <span style={{ color: 'orange' }}>{text}</span>
            } else {
              return <span style={{ color: 'rgb(227, 227, 70)' }}>{text}</span>
            }
          }
        },
        {
          title: '隐患状态',
          dataIndex: 'status',
          customRender: function(text) {
            if (text === '已整改') {
              return <span style={{ color: 'rgb(34, 173, 34)' }}>{text}</span>
            } else {
              return <span style={{ color: 'red' }}>{text}</span>
            }
          }
        },
        {
          title: '作业项目',
          dataIndex: 'workItem'
        },
        {
          title: '隐患描述',
          dataIndex: 'description',
          customRender: (text) => (
            <a-tooltip title={text}>
              {text.length > 5 ? text.substr(0, 5) + '...' : text}
            </a-tooltip>
          )
        }
      ],
      loadData: [],
      form: this.$form.createForm(this),
      QHSEOrganizationTree: [],
      defaultExpandedKeys: [],
      replaceFields: {
        children: 'children',
        title: 'title',
        key: 'workflowId',
        value: 'id',
        parentId: 'parentId'
      },
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0
      },
      selectWidth: 200,
      initialLoad: false
    }
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  mounted() {
    // 获取表格实例
    const table = this.$refs.table
    // 添加勾选改变事件监听器
    table.$on('selection-change', (selection) => {
      this.queryParam1.selectedRows = selection
      this.queryParam1.selectedRowKeys = selection.map(row => row.key)
    })
  },
  created() {
    this.getUnitTree()
    this.columns.push({
      title: '操作',
      width: '150px',
      dataIndex: 'action',
      scopedSlots: { customRender: 'action' }
    })
  },
  methods: {
    getQHSEDangerSelectUpload() {
      getQHSEDangerSelectUpload(this.queryParam).then((res) => {
        this.loadData = res.data.rows
        this.loading1 = false
        // console.log('this.loadData1', this.loadData)
      }).catch(() => {
        this.$message.warning('确认提交失败')
        this.this.loading1 = false
      })
    },
    // 一键提交
    submitSelectedRows() {
      this.loading = true
      this.tableLoading = true
      const select = this.queryParam1.selectedRows.map(rows => ({
        ...rows,
        checkOrganizationId: this.userInfo.currentOrganizationId
      }))
      const data = this.queryParam1.selectedRows

      const filteredData = this.loadData.filter(item => {
        return !data.some(d => d === item)
      })
      console.log(this.$refs.table)
      this.loadData = filteredData
      console.log('this.loadData', this.loadData)
      // this.loadData()
      gAddBatchList(select).then((res) => {
        this.loading = false
        this.tableLoading = false
        if (res.code === 200 && res.success === true) {
          console.log('res.resData', res.resData)
          console.log('res.data', res.data)
          if (res.resData.length > 0) {
            this.$message.warning('存在数据不完善，请修改后重新提交！')
            // 将不成功的数据插入到 loadData 的最前面
            this.loadData = res.resData.concat(this.loadData)
            this.queryParam1.selectedRowKeys = []
            this.queryParam1.selectedRows = []
            this.tableKey += 1
            console.log('this.loadData111', this.loadData)
          } else {
            this.$message.success('批量新增成功！')
            this.tableKey += 1
            this.queryParam1.selectedRowKeys = []
            this.queryParam1.selectedRows = []
          }
        } else {
          this.$message.error('批量新增失败，请重试！')
        }
      })
    },
    handleOrganNameClick(value, label, e) {
      if (value && label) {
        if (Array.isArray(label) && label.length > 0) {
          const selectedLabels = label.map(item => item.label)
          const selectedValues = value
          const lastSelectedLabel = selectedLabels[selectedLabels.length - 1]
          const lastSelectedValue = selectedValues[selectedValues.length - 1]
          this.queryParam.DangerOrganizationName = lastSelectedLabel
          this.queryParam.DangerOrganizationId = lastSelectedValue
          this.show = true
        } else {
          console.error('未选择单位或选择不正确')
        }
      }
    },
    transformData(data) {
      function transform(data) {
        return data.map(item => ({
          id: item.id,
          label: item.title,
          value: item.value,
          children: item.children ? transform(item.children) : []
        }))
      }
      return transform(data)
    },
    getUnitTree() {
      this.secondOraName.id = this.userInfo.secondOrganizationName
      getUnitTree(Object.assign(this.secondOraName)).then(res => {
        this.unitTree = this.transformData(res.data)
      })
    },
    handleDownloadTemplate() {
      window.location.href = './隐患导入模板.xlsx'
    },
    // 上传文件前，控制只能传pdf文件
    beforeUpload(file) {
        const isExcel = file.type === 'application/xls' || 'application/xlsx'
        if (!isExcel) {
          this.$message.error('只能上传 Excel 文件！')
          this.isPDF = false
          this.uploadedFile = null // 重置已上传的文件信息
        }
        return false
      },
    // 上传文件
    handleFileChange(info) {
        if (info.file.status !== 'removed') {
          const isExcel = info.file.type === 'application/xls' || 'application/xlsx'
          if (isExcel) {
          this.uploadError = true // 重置上传错误状态
          this.isChanged = true
          this.uploadedFile = info.file.response // 保存已上传的文件信息
          this.queryParam.file.name = info.file.name.split('.')[0]
          this.queryParam.fileName = info.file.name.split('.')[0]
          // this.defaultFileList = null
        //   console.log('fileName', this.queryParam.file.name)
          const file = info.file
          // if (file.status === 'done') {
          const reader = new FileReader()
          reader.onload = (e) => {
            // 将文件内容读取为 Base64 格式
            const base64String = e.target.result
            this.fileCode = base64String.split(',')[1]
            this.queryParam.file.base64Content = this.fileCode
            // console.log('queryParam', this.queryParam)
          }
          reader.readAsDataURL(file)
          } else {
            // this.visible = true // 文件不是PDF，隐藏组件
            this.uploadedFile = null // 重置已上传的文件信息
            this.queryParam = { // 清空相关的数据
              ...this.queryParam,
              fileName: '',
              file: {
                name: '',
                base64Content: ''
              }
            }
            this.isExcel = false
          }
        }
      },
    handleclick() {
      this.loading1 = true
      if (this.queryParam.DangerOrganizationName && this.queryParam.fileName) {
        this.queryParam.realName = this.userInfo.realName
        this.queryParam.userId = this.userInfo.userId
        this.queryParam.checkOrganizationName = this.userInfo.currentOrganizationName
        this.queryParam.checkOrganizationId = this.userInfo.currentOrganizationId
        this.queryParam.secondOrganizationId = this.userInfo.secondOrganizationId
        this.queryParam.thirdOrganizationId = this.userInfo.thirdOrganizationId
        // console.log('queryParam', this.queryParam)
        // console.log('this.$refs.table', this.$refs.table)
        // console.log('this.loadData', this.loadData)
        this.initialLoad = true
        this.getQHSEDangerSelectUpload()
      } else {
        this.$message.warning('请检查文件和单位名是否选择或上传')
        this.loading1 = false
      }
      },
    handleOk(record) {
      this.loadData = this.loadData.filter(item => item !== record)
    }
  }
}
</script>

<style lang="less" scoped>
/deep/.ant-table-tbody tr:nth-child(2n) {
  background-color: #f5f5f5
}
.table-operator {
  margin-bottom: 18px
}
button {
  margin-right: 8px
}
.search-row {
  display: flex;
  align-items: center
}
.search-buttons {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 10px
}
.scrollable-select {
  max-height: 200px;
  overflow-y: auto
}
</style>
